package com.xuyuan.concurrent.test;

public class TicketCounter {
    private int availableTickets;

    public TicketCounter(int availableTickets) {
        this.availableTickets = availableTickets;
    }

    public synchronized boolean bookTicket(int numTickets) {
        if (numTickets <= availableTickets) {
            // 检查是否还有足够的票可供预订
            System.out.println(Thread.currentThread().getName() + " 抢到了 " + numTickets + " 张票");
            availableTickets -= numTickets;
            return true;
        } else {
            System.out.println(Thread.currentThread().getName() + " 没有足够的票可供预订");
            return false;
        }
    }
}

class Main {
    public static void main(String[] args) {
        TicketCounter ticketCounter = new TicketCounter(10);

        // 创建多个线程模拟抢票
        Thread buyer1 = new Thread(() -> {
            ticketCounter.bookTicket(2);
        });

        Thread buyer2 = new Thread(() -> {
            ticketCounter.bookTicket(4);
        });

        Thread buyer3 = new Thread(() -> {
            ticketCounter.bookTicket(5);
        });

        // 启动线程
        buyer1.start();
        buyer2.start();
        buyer3.start();
    }
}